package cn.echase.ecare.yinfayun.utils;


import org.apache.commons.lang3.time.FastDateFormat;

import java.time.Instant;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 订单编号生成工具类
 **/
public class UcONGenerator {

    private static final FastDateFormat pattern = FastDateFormat.getInstance("yyyyMMddHHmmss");

    private static final AtomicInteger atomicInteger = new AtomicInteger(10000);

    private static ThreadLocal<StringBuilder> threadLocal = new ThreadLocal<StringBuilder>();


    /**
     * 长码生成策略
     *  20201116114351753590384993
     * @param lock uuid
     * @return
     */
    public static String getL(String lock) {
        if (Objects.isNull(threadLocal.get())){
            lock = Objects.isNull(lock) ? UUID.randomUUID().toString() : lock;
            StringBuilder builder = new StringBuilder(pattern.format(Instant.now().toEpochMilli()));// 取系统当前时间作为订单号前半部分
            builder.append(Math.abs(lock.hashCode()));// HASH-CODE
            builder.append(atomicInteger.getAndIncrement());// 自增顺序
            threadLocal.set(builder);
        }
        String no = threadLocal.get().toString();
        threadLocal.remove();
        return no;
    }

    /**
     * 短码生成策略
     * 1307891882965
     * @param lock
     * @return
     */
    public static String getS(String lock) {
        if (Objects.isNull(threadLocal.get())) {
            lock = Objects.isNull(lock) ? UUID.randomUUID().toString() : lock;
            StringBuilder builder = new StringBuilder(ThreadLocalRandom.current().nextInt(0, 999)); // 随机数
            System.out.println(builder);
            builder.append(Math.abs(lock.hashCode()));// HASH-CODE
            builder.append(atomicInteger.getAndIncrement());// 自增顺序
            threadLocal.set(builder);
        }
        String no = threadLocal.get().toString();
        threadLocal.remove();
        return no;
    }




}
